package top.linuyx.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import top.linuyx.pojo.entity.AccountEntity;
import top.linuyx.service.AccountService;
import top.linuyx.service.RoleService;
import top.linuyx.service.impl.AccountServiceImpl;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author Linuyx
 * @Description
 * @Date Created in 2021-04-08 21:41
 */
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    private AccountService accountService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取用户名
        String username = (String) authenticationToken.getPrincipal();
        //获取登录用户的角色
        String role = AccountServiceImpl.role.get();
        //使用完手动remove
        AccountServiceImpl.role.remove();

        //根据用户名和角色查询账户(角色来自AccountService的ThreadLocal)
        AccountEntity account = accountService.getAccountByUsernameAndRole(username, role);

        if (account != null) {
            return new SimpleAuthenticationInfo(
                    username,
                    account.getPassword(),
                    ByteSource.Util.bytes(account.getSalt()),
                    this.getName()
            );
        }

        return null;
    }

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户名
        String username = (String) principalCollection.getPrimaryPrincipal();

        //设置key
        String key = "role:" + username;
        //根据key从redis中获取Roles
        List<String> roles = redisTemplate.opsForList().range(key, 0, -1);
        if (roles.isEmpty()) {
            //根据用户名从数据库中获取Roles
            roles = roleService.listRoleByUsername(username);
            //将获取到的Roles存入redis中
            redisTemplate.opsForList().rightPushAll(key, roles);
            //设置过期时间
            redisTemplate.expire(key, 30, TimeUnit.MINUTES);
        }

        if (roles.size() != 0) {
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.addRoles(roles);
            return simpleAuthorizationInfo;
        }

        return null;
    }

}
